<?php

/**
 * @property $_store Core_Model_Store
 * @property $_stores Core_Model_DbTable_Stores
 */
class Store_StoreController extends YouNet_Controller_Action
{

	private $_id = null;

	/**
	 * @var Core_Model_Store
	 */
	private $_store = null;
	private $_stores = null;
	private $_id_page = null;

	
	public function preDispatch()
	{
		parent::preDispatch();
		
		$this->_stores = Core_Model_DbTable_Stores::getInstance();
		$this->_id = $this->_getParam('id', 0);
		$this->_id_page = $this->_getParam('id_page', null);
		if( $this->_id_page && !in_array($this->_id_page,$this->_social->getUserPageIds()) )
		{
			$this->_redirect($this->view->url(array('action' => 'list', 'id_page' => null)), array('prependBase' => false));
		}
		$this->view->render('store/select_fanpages.phtml');
		$this->view->use_admin_menu = true;
		$action = $this->_getParam('action');

		if (empty($this->_id))
		{
			if ($action == 'edit')
			{
				throw new Exception('Acccess is denined');
			}
		}
		else
		{
			//User cannot edit a store by using create action
			if ($action == 'create')
			{
				$this->_id = 0;
			}
		}
		$this->view->id_page = $this->_id_page;
		$this->_store = Core_Model_DbTable_Stores::getStoreByUser($this->_id, $this->_user);
	}

	public function indexAction()
	{
		$this->_redirect($this->view->url(array('action' => 'list')), array('prependBase' => false));
	}

	/**
	 *
	 * @staticvar string $form
	 * @return Store_Form_Store 
	 */
	private function _getForm()
	{
		static $form = null;
		if (!($form instanceof YouNet_Form))
		{
			if (empty($this->_store))
			{
				$form = new Store_Form_Store();
			}
			else
			{
				$form = new Store_Form_Store(array('store' => $this->_store));

				$action = $this->_getParam('action');
				if ($action == 'edit' && $this->_store->status == Core_Model_DbTable_Stores::STATUS_SHOWN)
				{
					$arrIdPages = $this->_social->getUserPageIds();
					$arrIdPages = array_diff($arrIdPages, $this->_store->getArrIdPages());
					if(!empty($arrIdPages))
					{
						$rowPublishedPages = Core_Model_DbTable_Pages::getInstance()->getPublishedStores($arrIdPages);
						if (!empty($rowPublishedPages))
						{
							$arrDisabledOptions = explode(',', $rowPublishedPages->id_pages);
							$form->getElement('fanpages')->setAttrib('disable', $arrDisabledOptions);
						}
					}
				}
			}

			$form->setCancelUrl($this->_getBackUrl());
			$form->setDownloadCssUrl($this->view->url(array('action' => 'downloadcss')));
			$this->view
					->headScript()
					->prependFile($this->view->baseUrl('/javascript/tiny_mce/jquery.tinymce.js'));
		}
		return $form;
	}

	private function _getBackUrl()
	{
		$backLink = $this->_getParam('back_link');
		if ($backLink != '')
		{
			$link = base64_decode($backLink);
			return urldecode($link);
		}
		return $this->view->url(array('action' => 'list', 'id' => null));
	}

	private function _generateForm($action)
	{
		$form = $this->_getForm();
		if (!isset($_POST['form_submitted']))
		{
			if (!empty($this->_store->id) && $action == 'edit')
			{
				$form->fill($this->_store);
			}

			if ($action == 'create')
			{
				$form->setDefaultFanpage($this->_id_page);
			}
		}
        
		$this->view->store = $this->_store;
        $this->view->action = $action;
		$this->view->form = $form;
		$this->render('form');
	}

	private function _handleCreateUpdate()
	{
		$action = $this->_getParam('action');
		
		if (isset($_POST['form_submitted']))
		{
			$form = $this->_getForm();
			if ($form->isValid($_POST))
			{
                $arrValues = $form->getValidValues($_POST);
                
                $banner_image = $form->getBannerImageName();
                $is_delete_banner = $this->_getParam('is_delete_banner', '');
                if(empty($banner_image))
                {
                    if(!empty($is_delete_banner))
                    {
                        $arrValues['banner_image'] = '';
                    }
                }
                else
                {
                    $arrValues['banner_image'] = $banner_image;
                }
                
                $css_name	= $form->getFanpageCssName();
                $is_delete_css = $this->_getParam('is_delete_css', '');
           
                if (empty($css_name))
                {
                	if (!empty($is_delete_css))
                	{
                		$arrValues['css']	=	'';
                	}
                }
                else 
                {
                	$arrValues['css']	=	$css_name;
                }
                
				$arrValues['action'] = $action;
				
				if($action=='create')
				{	
					$arrValues['id_user'] = $this->_id_user;
				}
				
				$status = $this->_store->createStoreFromParams($arrValues);
				if ($status)
				{
					$pagesTbl = new Core_Model_DbTable_Pages();
					$arrFanpageIds = array();
					if (!empty($arrValues[Store_Form_Store::FANPAGE_NAME]))
					{
						$arrFanpageIds = $arrValues[Store_Form_Store::FANPAGE_NAME];
					}
					$arrPageList = $this->_social->getPageList();
					$pagesTbl->updateFanpage($arrPageList, $arrFanpageIds, $this->_store->id);

					if ($action == 'create')
					{
						$flashMessage = $this->translate('MSG_SAVE_STORE_SUCCESSFUL');
					}
					else if ($action == 'edit')
					{
						$flashMessage = $this->translate('MSG_EDIT_STORE_SUCCESSFUL');
					}

					$this->_helper->flashMessenger->addMessage($flashMessage);

                    $this->disableAutoRender();
					Core_Util::redirect($this->view->url(array('controller' => 'product', 'action' => 'list', 'module' => 'store', 'id_store' => $this->_store->id, 'id_page' => $this->_id_page), '', true));
					
                    return;
				}
			}
		}

		$this->_generateForm($action);
	}

	public function createAction()
	{
		$this->_handleCreateUpdate();
		//Only show if is not exist errors
		$form = $this->_getForm();
		if( !empty($this->_store->id) && !$form->isErrors() )
		{
			$this->_store->doShow();
		}
	}

	public function editAction()
	{
		$this->_handleCreateUpdate();
	}

	public function showAction()
	{
		if (!empty($this->_id))
		{
			$this->_store->doShow();
			$errorMessage = $this->_store->getErrorMessage();
			if (sizeof($errorMessage))
			{
				$str_message = $this->translate('FAILED_TO_SHOW');
				$str_message .= '<p>' . $this->translate('MSG_MUST_BE_NO_PUBLISHED_STORE') . $this->_proccessErrorMessage($errorMessage) . '.</p>';
				$this->_helper->flashMessenger->addMessage($str_message);
			}
			else
			{
				$this->_helper->flashMessenger->addMessage($this->translate('MSG_SHOW_STORE_SUCCESSFULLY'));
			}
		}
		$this->_redirectBack();
	}

	private function _proccessErrorMessage($arrMsg)
	{
		$size = sizeof($arrMsg);
		if ($size == 1)
		{
			return $arrMsg[0];
		}
		else if ($size == 2)
		{
			return $arrMsg[0] . sprintf(' %s ', $this->translate('AND')) . $arrMsg[1];
		}
		else if ($size > 2)
		{
			$lastItem = $arrMsg[$size - 1];
			array_pop($arrMsg);
			return implode(', ', $arrMsg) . sprintf(' %s ', $this->translate('AND')) . $lastItem;
		}
	}

	public function hideAction()
	{
		if (!empty($this->_id))
		{
			$this->_store->doHide();
		}
		$this->_helper->flashMessenger->addMessage($this->translate('MSG_HIDE_STORE_SUCCESSFULLY'));
		$this->_redirectBack();
	}

	public function listAction()
	{
		$q = $this->_getParam('q');
		$page = $this->_getParam('page', 1);
		$arrSort = $this->_getParam('sort', array());
		$arrSort = array_merge($arrSort, array('q' => $q));

		if (!empty($this->_id_page))
		{
			$paginator = $this->_stores->findStoresByIdPage($this->_id_page, $arrSort, $page);
		}
		else
		{
			$paginator = $this->_stores->findStoresByUser($this->_id_user, $this->_social->getUserPageIds(), $arrSort, $page);
		}
		$this->view->messages = $this->_helper->flashMessenger->getMessages();
		$this->view->paginator = $paginator;
	}

	public function deleteAction()
	{
		if (!empty($this->_id))
		{
			$this->_store->doDelete();
		}
		$this->_helper->flashMessenger->addMessage($this->translate('MSG_DELETED_SUCCESSFULLY'));
		$this->_redirectBack();
	}
	public function downloadcssAction()
	{
		if (!empty($this->_store->css))
		{
			$file = $this->_store->getCssPath();
			header("Pragma: public", true);
			header("Expires: 0"); // set expiration time
			header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
			header("Content-Type: application/force-download");
			header("Content-Type: application/octet-stream");
			header("Content-Type: application/download");
			header("Content-Disposition: attachment; filename=".basename($file));
			header("Content-Transfer-Encoding: binary");
			header("Content-Length: ".filesize($file));
			die(file_get_contents($file));
		}		
	}
	private function _redirectBack()
	{
		$this->disableAutoRender();
		$backLink = $this->_getParam('back_link');
		if ($backLink != '')
		{
			$link = base64_decode($backLink);
			return Core_Util::redirect(urldecode($link));
		}

		$id_page = $this->_getParam('id_page');
		$url = '/store/store/list';

		if (!empty($id_page))
		{
			$url .= '/id_page/' . $id_page;
		}

		Core_Util::redirect($this->view->baseUrl($url));
	}
    
    public function settingFanPageAction()
    {
        // Adapter
        $id = $this->_getCurrentId();
        
        $model_tbl_setting = Settings_Model_DbTable_SettingsFanPage::getInstance();
        $model_row_setting = $model_tbl_setting->getRowSetting($id);
        
        $form = new Settings_Form_SettingFanPage($id,array(
            'default_thumnail_share' => STATIC_URL. "/media/style/image/logo_shared.png"
        ));
        
        $form->seLabelSubmit('Submit&Finish');
        $form->setClassSubmit('greenbutton');
        
        $message_success = "";
                            
        if (isset($_POST['form_submitted'])) {
            if ($form->isValid($_POST)) {
                // Get file
               // $arr_file_names = $form->getImages();
               // $values = array_merge($form->getValues(), $arr_file_names);
               $values = $form->mergDataPost($form->getValues());
              
                $row_setting_campaign = $model_tbl_setting->getRowSetting($id);
                $row_setting_campaign ->saveCampaign($values);

                // Message
                $message_success = $this->view->translate('MSG_UPDATE_SHARE_CONTENT_SUCCESS');
            } else {
                $form->populate($_POST);
            }
        } else {
            $setting_info = $model_tbl_setting->getSettingInfo($id);
           
            if ($setting_info)
            {
                if ($setting_info["share_image"])
                {
                    $share_img = STATIC_URL."/media/style/image/".$setting_info["share_image"];
                    //$form->setThumbnail($share_img);
                }
                $form->populate($setting_info->toArray());
            }  
        }
        // View
        $this->view->form = $form;
        $this->view->message = $message_success;
        
        $this->render('form');
        
    }
}
